package LeedCode_BinaryTree;

/**
 * Created with IntelliJ IDEA.
 * Description:判断两个二叉树是否对称
 * User: 阿宾
 * Date: 2024-11-21
 * Time: 10:44
 */
public class Demo5 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }
    public boolean isSameTree(TreeNode p, TreeNode q) {
        //判断空树
        if(p == null && q == null){
            return true;
        }
        //判断一个为空，一个不为空
        if(p == null || q == null){
            return false;
        }
        //都不空,判断值
        if(p.val != q.val){
            return false;
        }
        boolean ret1 = isSameTree(p.left,q.left);
        boolean ret2 = isSameTree(p.right,q.right);
        return ret1 && ret2;

    }
    public TreeNode invertTree(TreeNode root) {
        if(root != null){
            TreeNode tmp = root.left;
            root.left = root.right;
            root.right = tmp;

            invertTree(root.left);
            invertTree(root.right);
        }
        return root;
    }
    //综合了判断两个二叉树是否相同，翻转二叉树
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        //右子树翻转
        TreeNode newRight = invertTree(root.right);
        //对比左右子树是否相同
        return isSameTree(root.left,newRight);

    }

    //也可以是直接利用判断是否两树相同代码判断，不用翻转
    //==================================================
    public boolean isSameTreeChild(TreeNode p, TreeNode q) {
        //判断空树
        if(p == null && q == null){
            return true;
        }
        //判断一个为空，一个不为空
        if(p == null || q == null){
            return false;
        }
        //都不空,判断值
        if(p.val != q.val){
            return false;
        }
        boolean ret1 = isSameTreeChild(p.left,q.right);
        boolean ret2 = isSameTreeChild(p.right,q.left);
        return ret1 && ret2;

    }
    public boolean isSymmetric1(TreeNode root) {
        if(root == null){
            return true;
        }
        return isSameTreeChild(root.left,root.right);

    }
    public static void main(String[] args) {

    }
}
